package com.ihrm.system.controller;

import com.ihrm.common.controller.BaseController;
import com.ihrm.common.entity.PageResult;
import com.ihrm.common.entity.Result;
import com.ihrm.common.entity.ResultCode;
import com.ihrm.domain.system.Role;
import com.ihrm.domain.system.response.RoleResult;
import com.ihrm.system.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/sys")
public class RoleController extends BaseController{

    @Autowired
    private RoleService roleService;

    /**
     * 分配权限
     */
    @RequestMapping(value="/role/assignPerm",method = RequestMethod.PUT)
    public Result assignPerm(@RequestBody Map<String,Object> map){
        String roleId = (String) map.get("id");
        List<String> permIds = (List<String>) map.get("permIds");
        roleService.assignPerm(roleId,permIds);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 保存
     */
    @RequestMapping(value="/role",method = RequestMethod.POST)
    public Result save(@RequestBody Role role){
        //设置企业id
        role.setCompanyId(companyId);
        roleService.add(role);
        return new Result(ResultCode.SUCCESS,role);
    }

    /**u
     * 查询所有
     */
    @RequestMapping(value="/role",method = RequestMethod.GET)
    public Result findAll(int page,int size,@RequestParam Map map){
        //完成查询
        Page<Role> pageRole = roleService.findByPage(companyId, page, size);
        //构造返回结果
        PageResult<Role> pageResult = new PageResult<>(pageRole.getTotalElements(), pageRole.getContent());

        return new Result(ResultCode.SUCCESS,pageResult);
    }

    /**
     * 根据id查询
     */
    @RequestMapping(value="/role/{id}",method = RequestMethod.GET)
    public Result findById(@PathVariable(value = "id") String id){
        Role role = roleService.findById(id);
        RoleResult roleResult = new RoleResult(role);
        return new Result(ResultCode.SUCCESS,roleResult);
    }

    /**
     * 修改user
     */
    @RequestMapping(value="/role/{id}",method = RequestMethod.PUT)
    public Result update(@PathVariable(value = "id") String id,@RequestBody Role role){
        role.setId(id);
        roleService.update(role);
        return new Result(ResultCode.SUCCESS);
    }

    /**
     * 删除user
     */
    @RequestMapping(value="/role/{id}",method = RequestMethod.DELETE)
    public Result delete(@PathVariable(value = "id") String id){
        roleService.deleteById(id);
        return new Result(ResultCode.SUCCESS);
    }
}
